import router from '@/router/index';
import { Message } from 'element-ui';
import defaultSettings from '@/settings';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import { checkLoginToken } from '@/utils/Token'; // get token from cookie

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const title = defaultSettings.title || '云裳信息化平台';

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start();
  // set page title
  document.title = to.meta.title || title;
  
  // check is white router
  if (to.meta.isNotCheckToken) {
    next();
    NProgress.done();
  } else {
    // 拦截
    const routesString = localStorage.getItem('CurrentUserRoutesModule');
    if (routesString && routesString.indexOf(to.name) == -1) {
      next(`/404`);
      NProgress.done();
      return;
    }
    // determine whether the user has logged in
    if (checkLoginToken()) {
      next();
      NProgress.done();
    } else {
      Message.error('用户未登录或登录已过期，请重新登录!');
      /* has no token*/
      // other pages that do not have permission to access are redirected to the login page.login
      next(`/?redirect=${to.path}`);
      NProgress.done();
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
})
